﻿using LiveHub.Share.DataModels;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;

namespace LiveHub.WebApi.Models;

public class LiveChatHub(HubContext context) : Hub
{
    public const string HubUrl = "/LiveChat";

    public async Task SendMessage(string groupId, MessageModel message,bool isAdd)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, groupId);
        
        if (isAdd)
        {
            var group = await context.Groups.
                FirstOrDefaultAsync(x => x.GroupId == groupId);
            if (group == null) return;
            var user = await context.Users.FirstOrDefaultAsync(x => x.UserId == message.UserId);
            if (user == null) return;
            message.MessageId = message.ToString();
            message.User = user;
            group.Messages.Add(message);
        }
        else
        {
            var messageModel = await context.Messages.FirstOrDefaultAsync(x => x.MessageId == message.MessageId);
            if (messageModel == null) return;
            context.Messages.Remove(messageModel);
        }
        await context.SaveChangesAsync();
        await Clients.Group(groupId).SendAsync("ReceiveMessage", message, isAdd);
    }
}